﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
using System.Runtime.InteropServices;

namespace Profari_Heldur_Utan_Um_Prof
{
    public partial class EditTask : Form
    {
        #region SQL Connection
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt ");
        private static DataTable dt = new DataTable();
        private static DataSet ds = new DataSet();
        SqlDataReader r = null;
        #endregion

        #region Static Variables
        public static string cmbSelectGroupNameValue;
        public static List<Tasks> taskList = new List<Tasks>();
        public static ArrayList TaskID = new ArrayList();
        public static ArrayList newTaskIds = new ArrayList();
        public static int globalGroupsID;
        public static int globalEvaluationID;
        public static string selectedExistingGroup;
        public static string webPageUrl;
        public static string groupName;
        public static string evaluationName;
        #endregion

        #region Variables
        public int createTaskPressed = 0;
        #endregion

        
        public struct Tasks
        {
            public string createNewGroup;
            public string nameOfEvaluation;
            public string userWebPage;
            public string task;
            public string taskDescript;
            public string scenarioTask;
        }

        public EditTask()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            globalGroupsID = ListOfProjects.globalGroupID;
            globalEvaluationID = ListOfProjects.globalEvaluationID;
        }

        public EditTask(int groupsID, int evaluationID)
        {
            globalGroupsID = groupsID;
            globalEvaluationID = evaluationID;
            InitializeComponent();
        }

        private void EditTask1_Load(object sender, EventArgs e)
        {
            if (chkExistingGroup.Checked == true)
            {
                cmbExistingGroup.SelectedItem = cmbSelectGroupNameValue;
            }
            

            FillTaskListBox();
            FillTextBox();

            chkDescriptionTask.Checked = false;
            riTaskScenario.Enabled = false;

            btnUpdate.Hide();
            lblWarningText.Hide();
            btnCreateTask.Hide();

            getGroupName();
        }

        #region Functions

        //Controls if textbox or combobox should be shown.
        public void setGroupName()
        {
            if (chkExistingGroup.Checked)
            {
                cmbExistingGroup.Visible = true;
                cmbExistingGroup.SelectedItem = cmbSelectGroupNameValue;
                //If the user goes between forms the value he had chosen in the form will be show
                cmbExistingGroup.Text = cmbSelectGroupNameValue;
                cmbExistingGroup.Show();
                txtNewGroupName.Enabled = false;
            }
            else
            {
                cmbExistingGroup.Visible = false;
                txtNewGroupName.Enabled = true;
            }
        }
        #endregion

        #region Code so user can do changes on runtime
        private void lbTaskListBox_SelectedIndexChanged(object sender, EventArgs e)
        {

            foreach (Tasks temp in taskList)
            {
                if (temp.task == (string)lbTaskListBox.SelectedItem)
                {
                    txtTaskName.Text = temp.task;
                    riDescriptionOfTask.Text = temp.taskDescript;
                    if (temp.scenarioTask != "")
                    {
                        riTaskScenario.Text = temp.scenarioTask;
                        chkDescriptionTask.Checked = true;
                    }
                    else
                    {
                        riTaskScenario.Text = "";
                        chkDescriptionTask.Checked = false;
                    }
                }
            }
            btnCreate.Hide();
            btnUpdate.Hide();
            btnCreateTask.Show();

        }

        private void chkExistingGroup_CheckedChanged_1(object sender, EventArgs e)
        {
            if (chkExistingGroup.CheckState == CheckState.Checked)
            {
                cmbExistingGroup.Show();
            }
            else
            {
                cmbExistingGroup.Hide();
            }
        }
        #endregion

        #region Events

        private void EditTask1_Load(int groupsID, int evaluationID)
         {
             setGroupName();

             btnUpdate.Hide();
             lblWarningText.Hide();
             lblStar6.Hide();

             getGroupName();
             if (cmbExistingGroup.Items.Count == 0)
                 chkExistingGroup.Enabled = false;
             if (chkDescriptionTask.Checked == false)
             {
                 riTaskScenario.Enabled = false;
             }

         }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //txtWebPage.Text = webBrowser1.Document.Url.ToString();
            //toolStripUrlText.Text = webBrowser1.Document.Url.ToString();
        }

        private void chkExistingGroup_CheckedChanged(object sender, EventArgs e)
        {
            if (chkExistingGroup.Checked == true)
            {
                cmbExistingGroup.Visible = true;
                txtNewGroupName.Enabled = false;
            }
            else
            {
                cmbExistingGroup.Visible = false;
                txtNewGroupName.Enabled = true;
            }
        }

        private void chkDescriptionTask_CheckedChanged(object sender, EventArgs e)
        {
            if (chkDescriptionTask.CheckState == CheckState.Checked)
            {
                riTaskScenario.Enabled = true;
                lblStar6.Show();
            }
            else
            {
                riTaskScenario.Enabled = false;
                lblStar6.Hide();
            }

        }

        #endregion

        #region Buttons
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //If cancel button is pressed user get's a question if he wants to quit making a project or not
            DialogResult cancelProject = MessageBox.Show("Are you sure you want to stop editing?", "Quit", MessageBoxButtons.YesNo);
            if (cancelProject == DialogResult.Yes)
            {
                System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTesterInterface));
                testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                testerInterface.Start();
                EditTask.taskList.Clear();
                EditTask.TaskID.Clear();
                EditTask.newTaskIds.Clear();
                this.Close();
            }
        }

        private void toolStripBtnBack_Click(object sender, EventArgs e)
        {
            if (webBrowser1.CanGoBack)
            {
                webBrowser1.GoBack();
            }
        }

        private void toolStripBtnForward_Click(object sender, EventArgs e)
        {
            if (webBrowser1.CanGoForward)
            {
                webBrowser1.GoForward();
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(txtWebPage.Text);
            toolStripUrlText.Text = txtWebPage.Text;
        }

        private void btnCreateTask_Click(object sender, EventArgs e)
        {
            txtTaskName.Clear();
            riDescriptionOfTask.Clear();
            chkDescriptionTask.Checked = false;
            riTaskScenario.Clear();
            btnCreate.Show();
            btnUpdate.Hide();
            btnCreateTask.Hide();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if ((chkExistingGroup.Checked == true && cmbExistingGroup.SelectedIndex == -1)
                || txtNewGroupName.Text == "" || txtEvaluationName.Text == ""
                || txtWebPage.Text == "" || txtTaskName.Text == "" || riDescriptionOfTask.Text == ""
                || (chkDescriptionTask.Checked == true && riTaskScenario.Text == ""))
            {
                MessageBox.Show("Please fill in the boxes marked with red star");
                lblWarningText.Show();
                lblWarningText.Text = "Please type some text that are marked with red star";
            }
            else
            {
                createTaskPressed++;
                lbTaskListBox.Items.Add(txtTaskName.Text);
                if (chkDescriptionTask.CheckState == CheckState.Checked)
                {
                    taskList.Add(new Tasks()
                    {
                        task = txtTaskName.Text,
                        taskDescript = riDescriptionOfTask.Text,
                        scenarioTask = riTaskScenario.Text
                    });
                }
                else if(chkDescriptionTask.CheckState == CheckState.Unchecked)
                {
                    riTaskScenario.Text = "";
                    taskList.Add(new Tasks()
                    {
                        task = txtTaskName.Text,
                        taskDescript = riDescriptionOfTask.Text,
                        scenarioTask = riTaskScenario.Text
                    });
                    txtTaskName.Clear();
                    riDescriptionOfTask.Clear();
                    chkDescriptionTask.Checked = false;
                    riTaskScenario.Clear();

                    cmbExistingGroup.Visible = false;
                    chkExistingGroup.Checked = false;
                    txtNewGroupName.Enabled = false;
                    txtWebPage.Enabled = false;
                    txtWebPage.Enabled = false;
                
                }
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            int selected = lbTaskListBox.SelectedIndex;
            lbTaskListBox.Items.RemoveAt(selected);
            lbTaskListBox.Items.Insert(selected, txtTaskName.Text);
            taskList.RemoveAt(selected);
            var task = new Tasks() { task = txtTaskName.Text, taskDescript = riDescriptionOfTask.Text, scenarioTask = riTaskScenario.Text };
            if (chkDescriptionTask.CheckState == CheckState.Unchecked)
            {
                chkDescriptionTask.Checked = false;
                riTaskScenario.Text = "";
                taskList.Insert(selected, task);
            }
            else
            {
                taskList.Insert(selected, task);
            }
            txtTaskName.Clear();
            riDescriptionOfTask.Clear();
            chkDescriptionTask.Checked = false;
            riTaskScenario.Clear();
            btnUpdate.Hide();
            btnCreate.Show();
            //hugsanlega henda út
            /*btnGo.Enabled = false;
            txtNewGroupName.Enabled = false;
            txtEvaluationName.Enabled = false;
            txtWebPage.Enabled = false;*/
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            updateGroupName();
            updateEvaluationName();
            updateUrl();
            
            getTaskID();
            updateTasks();
            insertTasks();
            getNewTaskIds();
            insertEvaluationTask();
            System.Threading.Thread listOfProjects = new System.Threading.Thread(new System.Threading.ThreadStart(OpenListOfProjects));
            listOfProjects.SetApartmentState(System.Threading.ApartmentState.STA);
            listOfProjects.Start();
            EditTask.taskList.Clear();
            EditTask.TaskID.Clear();
            EditTask.newTaskIds.Clear();
            this.Close();
        }

        private void btnEditTask_Click(object sender, EventArgs e)
        {
            btnUpdate.Show();
            btnCreate.Hide();

            if (lbTaskListBox.Items.Count == 0)
            {
                MessageBox.Show("There are no items to edit, please create task first");
            }
            else
            {
                foreach (Tasks temp in taskList)
                {
                    if (temp.task == (string)lbTaskListBox.SelectedItem)
                    {
                        txtTaskName.Text = temp.task;
                        riDescriptionOfTask.Text = temp.taskDescript;
                        if (temp.scenarioTask != "")
                        {
                            riTaskScenario.Text = temp.scenarioTask;
                            chkDescriptionTask.Checked = true;
                        }
                    }

                    txtNewGroupName.Enabled = true;
                    txtWebPage.Enabled = true;
                    txtEvaluationName.Enabled = true;
                }
            }
        }

        private void btnDeleteTask_Click(object sender, EventArgs e)
        {
            DialogResult deleteTasks = MessageBox.Show("Are you sure you want to delete this Task?", "Quit", MessageBoxButtons.YesNo);
            if (deleteTasks == DialogResult.Yes)
            {
                int selectedindex = lbTaskListBox.SelectedIndex;
                taskList.RemoveAt(selectedindex);
                lbTaskListBox.Items.RemoveAt(selectedindex);

                btnCreate.Show();
                btnEditTask.Hide();
            }
        }

        private void btnEditLayout_Click(object sender, EventArgs e)
        {
            getTaskID();
            webPageUrl = txtWebPage.Text;
            groupName = txtNewGroupName.Text;
            evaluationName = txtEvaluationName.Text;
            System.Threading.Thread editCheckBoxes = new System.Threading.Thread(new System.Threading.ThreadStart(OpenEditCheckBoxes));
            editCheckBoxes.SetApartmentState(System.Threading.ApartmentState.STA);
            editCheckBoxes.Start();
            this.Close();   
        }        
        
        private void btnCancelGoBack_Click(object sender, EventArgs e)
        {
            DialogResult cancelgroups = MessageBox.Show("Are you sure you want to cancel editing? your changes will not be saved", "Quit", MessageBoxButtons.YesNo);
            if (cancelgroups == DialogResult.Yes)
            {
                System.Threading.Thread listOfGroups = new System.Threading.Thread(new System.Threading.ThreadStart(OpenListOfProjects));
                listOfGroups.SetApartmentState(System.Threading.ApartmentState.STA);
                listOfGroups.Start();
                this.Close();
            }
        }

        #endregion

        #region Sql Commands
        public void FillTextBox()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT G.name, E.name, E.url FROM GroupEvaluations GE INNER JOIN Groups G ON GE.groupsID = G.id INNER JOIN Evaluation E ON GE.evaluationID = E.id WHERE G.id='" + globalGroupsID + "';", con);

                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    string groupName = "";
                    string evalName = "";
                    string evalUrl = "";
                    for (int i = 0; i < r.FieldCount; i++)
                    {
                        groupName += r.GetValue(i).ToString();
                        evalName += r.GetValue(++i).ToString();
                        evalUrl += r.GetValue(++i).ToString();
                    }

                    txtNewGroupName.Text = groupName;
                    txtEvaluationName.Text = evalName;
                    txtWebPage.Text = evalUrl;
                }
                
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }

            webBrowser1.Navigate(txtWebPage.Text);
            toolStripUrlText.Text = txtWebPage.Text;
        }

        private void FillTaskListBox()
        {
            lbTaskListBox.Items.Clear();
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT T.name, T.taskDescription, T.scenariosDescription FROM Task T INNER JOIN EvaluationTask ET ON ET.taskID = T.id WHERE ET.evaluationID=" + globalEvaluationID, con);
                
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    //lbTaskListBox.Items.Add(r["name"]);
                    lbTaskListBox.Items.Add(r.GetString(0));

                    if (r[2] == DBNull.Value)
                        taskList.Add(new Tasks() 
                                    { task = r.GetString(0), 
                                      taskDescript = r.GetString(1),
                                      scenarioTask = ""});
                    else
                    {
                        taskList.Add(new Tasks() 
                                    { task = r.GetString(0), 
                                      taskDescript = r.GetString(1), 
                                      scenarioTask = r.GetString(2) });
                        chkDescriptionTask.Checked = true;
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        private void updateGroupName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Groups SET name='" + txtNewGroupName.Text + "' WHERE id='" + globalGroupsID + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    string thisrow = "";
                    for (int i = 0; i < r.FieldCount; i++)
                        thisrow += r.GetValue(i).ToString();

                    txtNewGroupName.Text += thisrow;
                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateEvaluationName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET name='" + txtEvaluationName.Text + "' where ID='" + globalEvaluationID + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    string thisrow = "";
                    for (int i = 0; i < r.FieldCount; i++)
                        thisrow += r.GetValue(i).ToString();

                    txtEvaluationName.Text += thisrow;
                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateUrl()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET url='" + txtWebPage.Text + "' WHERE id='" + globalEvaluationID + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    string thisrow = "";
                    for (int i = 0; i < r.FieldCount; i++)
                        thisrow += r.GetValue(i).ToString();

                    txtWebPage.Text += thisrow;
                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void getNewTaskIds()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP " + taskList.Count+ " id FROM Task ORDER BY ID desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        newTaskIds.Add(r.GetInt32(0));
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateTasks()
        {
            int id = 0;
            List<Tasks> temp = new List<Tasks>(taskList);
            foreach (Tasks TaskObj in taskList)
            {
                if (id == TaskID.Count)
                    break;               
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("Update Task set name=@txtname, taskDescription=@txtTaskDescript, scenariosDescription=@txtScenario WHERE id="+TaskID[id], con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                    temp.Remove(TaskObj);
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
                id++;
                taskList = temp;
            }
        }

        private void insertTasks()
        {
            foreach (Tasks TaskObj in taskList)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO Task(name, taskDescription, scenariosDescription) VALUES(@txtname, @txtTaskDescript, @txtScenario)", con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void insertEvaluationTask()
        {
            foreach (int id in newTaskIds)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO EvaluationTask(evaluationID, taskID, introBeforeEvaluationID) values(@evaluationID, @taskID, @introBFEvalID)", con);
                    cmd.Parameters.AddWithValue("@evaluationID", globalEvaluationID == 0 ? DBNull.Value : (object)globalEvaluationID);
                    cmd.Parameters.AddWithValue("@taskID", id == 0 ? DBNull.Value : (object)id);
                    cmd.Parameters.AddWithValue("@introBFEvalID", DBNull.Value);
                    cmd.ExecuteNonQuery();

                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());

                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void getTaskID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT T.id FROM Task T INNER JOIN EvaluationTask ET ON ET.taskID = T.id WHERE ET.evaluationID=" + globalEvaluationID, con);
                     r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        TaskID.Add(r.GetInt32(0));
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void getGroupName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT name FROM Groups", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    cmbExistingGroup.Items.Add(r["Name"]);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
            Hashtable hash = new Hashtable();
            int cnt = 0;
            foreach (string item in cmbExistingGroup.Items)
            {
                if (!hash.ContainsValue(item))
                {
                    hash[cnt++] = item;
                }
            }

            cmbExistingGroup.Items.Clear();
            for (int i = 0; i < cnt; i++)
            {
                cmbExistingGroup.Items.Add(hash[i]);
            }
        }

        private void getGroupID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT id FROM Groups WHERE name='" + (string)cmbExistingGroup.SelectedItem + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    globalGroupsID = r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        #endregion

        //The Open forms functions makes it able to move between forms and close the first form when the second one is opened
        #region OpenForms
        public void OpenTesterInterface()
        {
            Application.Run(new TesterInterface());
        }
        public static void OpenListOfProjects()
        {
            Application.Run(new ListOfProjects());
        }
        public static void OpenEditCheckBoxes()
        {
            Application.Run(new EditCheckboxes());
        }

        #endregion

        private void cmbExistingGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedExistingGroup = (string)cmbExistingGroup.SelectedItem;
        }

        



        

    }
}
